#!/usr/bin/env python

import os, sys
 

if len(sys.argv) < 3 or  len(sys.argv) > 4:
	print 'cl_charger_taut.py  <directory with charger.py and tautomerizer.py> <SDF:True|False> (<Supplier Id numer field>)'
	sys.exit(1)

sdf  = sys.argv[2]
if sdf == 'True':
	sdf = True
	type = '.sdf'
	if len(sys.argv) <> 4:
		print 'cl_charger_taut.py  <directory with charger.py and tautomerizer.py> <SDF:True|Fase> (<Supplier Id numer field>)'
		sys.exit(1)
	else:
		id_field = sys.argv[3]
else:
	type = '.smi'
	id_field = 'xxx' #is not needed
	sdf = False


files = os.listdir('./')

clean_list = []
max_file_number = 0

#remove all none .smi from files
for i in files:
	if (sdf and i[-4:] == '.sdf') or (not sdf and i[-4:] == '.smi'):
		clean_list.append(i)
		start = i.find('_') + 1
		end = i.find('.')
		number = int(i[start:end])
		if number > max_file_number:
			max_file_number = number

files = clean_list

path = sys.argv[1]


files.sort()


#make start file, suitable for array job, assumes that smiles files are numbered
#assume that counting starts with 1	for i in files:
#first_file = files[0]
#prefix = first_file[0:first_file.find('_')]
#print prefix
#start_file = open(prefix + '.bin', 'w')

#start_file.write('#BSUB -q short\n')
#start_file.write('#BSUB -J ' + prefix + '_charg_taut_Array[1-' + str(max_file_number) + ']\n')
#start_file.write('#BSUB -o "%J.output.%I"\n')
#start_file.write('#BSUB -e "%J.err.%I"\n')


#start_file.write(path + 'charger.py ' + prefix + '_\$LSB_JOBINDEX' + first_file[-4:] + ' ' + prefix + '_charged_\$LSB_JOBINDEX' + first_file[-4:] + ' False 7 0' + ' ' + id_field)

#start_file.write(path + '/tautomerizer.py ' + prefix + '_\$LSB_JOBINDEX.smi ' + prefix + '_taut_\$LSB_JOBINDEX.smi')
#start_file.close()

#os.system('chmod 755 ' + prefix + '.bin') 
#command = 'bsub ' + prefix + '.bin'

#print command
#os.system(command)

for i in files:
	file_name = i[:-4] + '_start.bin'
	start_file = open(file_name, 'w')
	start_file.write("#BSUB-q short             	# Job queue\n#BSUB-o job.output              # output is sent to file job.output\n#BSUB-J test_mogon              # name of the job\n")
	start_file.write(path + '/charger.py  ')
	start_file.write(i + ' ' + i[:-4] + '_charged.smi False 7 0 '  + id_field + ' > ' + i[:-4] + '_charger.log\n')

	start_file.write(path + '/tautomerizer.py  ')
	start_file.write(i[:-4] + '_charged.smi' + ' ' + i[:-4] + '_charged_taut.smi False  > ' + i[:-4] + '_taut.log')

	start_file.close()
	os.system('chmod 744 '  + file_name)
	command = 'qsub -q short ' + file_name
	print command
	os.system(command)



	
	
